package com.aisile.common.exception;

import com.aisile.model.common.dtos.ResponseResult;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * 抓取controller 层中出现的异常 （1. 不可预知异常 2 可预知异常）
 *
 * @Auther:yry
 * @Date:2024/7/11 0011
 * @VERSON:1.0
 */
@Slf4j
@ControllerAdvice
public class ExceptionWorkerAdvice {


    // 构建immutableMap
    public static ImmutableMap<Class<? extends Exception>,ResponseResult> EXCEPTIONS;
    public static ImmutableMap.Builder<Class<? extends Exception>,ResponseResult> builder = ImmutableMap.builder();

    static {
        builder.put(NullPointerException.class,ResponseResult.errorResult(30000,"数据不能为空！"));
        builder.put(IndexOutOfBoundsException.class,ResponseResult.errorResult(30001,"超出数据限制！"));
        builder.put(IOException.class,ResponseResult.errorResult(30002,"文件转换出现问题！"));
        builder.put(NumberFormatException.class,ResponseResult.errorResult(30003,"数据转换出现问题！"));
        builder.put(ArithmeticException.class,ResponseResult.errorResult(30004,"数学计算、运算出现问题！"));
        builder.put(HttpMessageNotReadableException.class,ResponseResult.errorResult(30005,"请求没按照接口规则！"));

    }

    /**
     * 处理不可预知的异常
     *
     * @return
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public ResponseResult NotKnowException(Exception e) {
        e.printStackTrace();
        if(EXCEPTIONS == null){
            EXCEPTIONS = builder.build();
        }
        ResponseResult responseResult =  EXCEPTIONS.get(e.getClass());
        if(responseResult == null){
            // 记录日志
            return ResponseResult.errorResult(99999,"请联系管理员或稍后重试...");
        }
        return responseResult;
    }

    /**
     * 处理可预知的异常
     *
     * @return
     */
    @ExceptionHandler(value = {CustomException.class})
    @ResponseBody
    public ResponseResult KnowException(CustomException e) {
        e.printStackTrace();
        // 记录日志
        return e.getResponseResult();
    }

}
